<?php
namespace Crm\Domain;

use Crm\Common\MetaData as MetaData;
use Crm\Common\Pager as Pager;

class Project
{
	/**
	 * pdo连接。
	 * 
	 * @var object
	 * @access pdo
	 */
	public $pdo;

    public $metaData;
    public $baseCode;
    public $province_code;//省编码
    public $city_code;//城市编码
    public $pm_level_option;
    public $borough_option;//行政区
    public $circle_option;//环线
    public $direction_option;//方位
    public $region_option;//片区
    public $business_region_option;//商圈
    public $build_year_option;//建筑年代
    public $pic_option;// 图片类型
    public $toward_option; //房屋朝向
    public $fitment_type_option; //内部装修
    public $build_plan_option;//工程进度
    public $build_struct_option;//建筑结构
    public $build_shape_option; //建筑形态
    public $build_type_option;  //建筑类型
    public $attribute_option;   //项目属性
    public $level_option;       //项目定位
    public $status_option;       //项目销售状态
    public $tube_option;        //地铁
    public $digest_option;      //推荐等级
    public $view_liv_option;    //小区景观
    public $build_suffix_option;    //楼栋后缀

    public function __construct()
    {
        $this->pdo = \PhalApi\DI()->pdo;

        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->metaData = new MetaData();

        $this->pm_level_option = $this->metaData->getPairBaseCodeByType(223);//物业等级
        $this->borough_option = $this->metaData->getPairBaseCodeByType($this->city_code);//区域列表
        $this->circle_option = $this->metaData->getPairBaseCodeByType(211);//获取环线
        $this->direction_option = $this->metaData->getPairBaseCodeByType(205);//获取方位
        $this->build_year_option      = $this->metaData->getPairBaseCodeByType(229);
        $this->pic_option             = $this->metaData->getPairBaseCodeByType(209);
        $this->toward_option          = $this->metaData->getPairBaseCodeByType(215);
        $this->fitment_type_option    = $this->metaData->getPairBaseCodeByType(219);
        $this->build_plan_option      = $this->metaData->getPairBaseCodeByType(230);
        $this->build_struct_option    = $this->metaData->getPairBaseCodeByType(201);
        $this->build_shape_option     = $this->metaData->getPairBaseCodeByType(234);
        $this->build_type_option      = $this->metaData->getPairBaseCodeByType(235);
        $this->attribute_option       = $this->metaData->getPairBaseCodeByType(236);
        $this->level_option           = $this->metaData->getPairBaseCodeByType(237);
        $this->status_option          = $this->metaData->getPairBaseCodeByType(222);
        $this->tube_option            = $this->metaData->getPairBaseCodeByType(238);
        $this->digest_option          = $this->metaData->getPairBaseCodeByType(244);
        $this->view_liv_option        = $this->metaData->getPairBaseCodeByType(239);
        $this->build_suffix_option    = $this->metaData->getPairBaseCodeByType(240);
    }

	public function tabbar($state='base',$project_id){
		$tabbale = '<ul class="nav nav-tabs">';
        $lilist = array(
            'info'   =>array('url'=>'edit?project_id=','icon'=>'','title'=>'基础信息')
        );
        //判断该项目是否存在物业类型
        $sql = "select pm_type from fc_project where id=".$project_id;
        $pmType = $this->pdo->getRow($sql);
        $_pmTypes = explode(',',$pmType['pm_type']);
        if(count($_pmTypes)>0) {
            foreach ($_pmTypes as $k => $v) {
                switch($v){
                    case '20303'://别墅
                        $lilist['villa']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'别墅');
                        break;
                    case '20308'://商业
                        //$lilist['business']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'商业');
                        $lilist['office']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'写字楼');
                       break;
                    case '20306'://写字楼
                        $lilist['office']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'写字楼');
                        break;
                    case '20302'://公寓
                        //$lilist['apartment']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'新房');
                        $lilist['office']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'写字楼');
                        break;
                    case '20301'://住宅
                        $lilist['house']=array('url'=>'editPmType?pm_type='.$v.'&project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'住宅');
                        break;
                    default:
                        break;
                }
            }
        }

        //$lilist['dynamic']=array('url'=>'listDynamic?project_id=','icon'=>'fa fa-bullhorn mrs','title'=>'动态');
		//$lilist['table']=array('url'=>'listTable?project_id=','icon'=>'fa fa-th mrs','title'=>'楼盘表');
        //$lilist['license']=array('url'=>'listlicense?project_id=','icon'=>'fa fa-th mrs','title'=>'预售证');
        $lilist['pic']=array('url'=>'listPic?project_id=','icon'=>'fa fa-picture-o mrs','title'=>'图库');

		foreach($lilist as $key=>$val){
			$icon = '';
			if(empty($val['icon']))$icon = '<i class="'.$val['icon'].'"></i>';
			if($key==$state){
				$tabbale.= '<li class="active"><a href="javascript:void(0);">'.$icon.$val['title'].'</a></li>';
			}else{
				$tabbale.= '<li><a href="'.$val['url'].$project_id.'">'.$icon.$val['title'].'</a></li>';
			}
		}
		$tabbale .= '</ul>';
		return $tabbale;
	}

	/* 项目搜索 */
    public function search($data,$data_type="base"){
        $page_info = "";//url参数
        $orderField = isset($data['sort']) ? $data['sort'] : 'sort';//排序字段
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc,id desc';//排序类型
        $pageSize = 15;//分页，每页显示数量
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'where 1=1 ';
        /*
        if($_SESSION['isadmin'] != 1){
            //增加个人数据限制，用户只允许看到自己负责的项目
            $userIds = $this->session->user_id;
            //上级可以看到自己下级人员的项目，但是依然需要配置操作权限才可更改数据
            $this->loadModel('cyzt_companylist');
            $roleId = $this->session->role_id;
            $rolelist = $this->cyzt_companylist->getSubRoleList($roleId);
            $where = $where.'and owner_uid in ('.$userIds.') ';
        }
        */

        //城市区域
        $city_code = isset($data['city_code'])?$data['city_code']:'';
        if($city_code!='') {
            $where .= " and city_code='{$city_code}'";
            $page_info .="city_code=".$city_code."&";
            $filter['city_code'] = $city_code;
            $filter['city_value'] = '城市';
        }

        //是否有效
        $flag = isset($data['flag'])?$data['flag']:'1';
        if($flag!= ''){
            $where .= " and flag={$flag}";
            $page_info .="flag=".$flag."&";
            $filter['flag'] = $flag;
        }

        //行政区
        $borough = isset($data['borough'])?$data['borough']:'0';
        if($borough!= '0'){
            $where .= " and borough='{$borough}'";
            $page_info .="borough=".$borough."&";
            $filter['borough'] = $borough;
            $filter['borough_value'] = '不限';
        }else{
            $filter['borough'] = $borough;
            $filter['borough_value'] = '行政区';
        }

        $pm_type = isset($data['pm_type'])?$data['pm_type']:'0';
        if($pm_type != "0"){
            $where .=" and `pm_type` like '%".$pm_type."%'";
            $page_info .="pm_type=".$pm_type."&";
            $filter['pm_type'] = $pm_type;
            $filter['pm_type_value'] = '不限';
        }

        $project_type = isset($data['project_type'])?$data['project_type']:'0';
        if($project_type != "0"){
            $where .=" and `project_type` = '{$project_type}'";
            $page_info .="project_type=".$project_type."&";
            $filter['project_type'] = $project_type;
        }

        $is_boss = isset($data['is_boss'])?$data['is_boss']:'';
        if($is_boss != ''){
            $where .=" and `is_boss` = '{$is_boss}'";
            $page_info .="is_boss=".$is_boss."&";
            $filter['is_boss'] = $is_boss;
        }

        $is_poster = isset($data['is_poster'])?$data['is_poster']:'';
        if($is_poster != ''){
            $where .=" and `is_poster` = '{$is_poster}'";
            $page_info .="is_poster=".$is_poster."&";
            $filter['is_poster'] = $is_poster;
        }

        $digest = isset($data['digest'])?$data['digest']:'';
        if($digest != ''){
            $where .=" and `digest` = {$digest}";
            $page_info .="digest=".$digest."&";
            $filter['digest'] = $digest;
        }

        $developer_id = isset($data['developer_id'])?$data['developer_id']:'';
        if($developer_id != ''){
            $where .=" and `developer_id` = {$developer_id}";
            $page_info .="developer_id=".$developer_id."&";
            $filter['developer_id'] = $developer_id;
        }

        $mall_id = isset($data['mall_id'])?$data['mall_id']:'';
        if($mall_id != ''){
            $where .=" and `mall_id` = {$mall_id}";
            $page_info .="mall_id=".$mall_id."&";
            $filter['mall_id'] = $mall_id;
        }

        $key = isset($data['key'])?trim($data['key']):'';
        if($key!=''){
            $where .= " and name like '%".$key."%'";
            $page_info .="key=".$key."&";
            $filter['key'] = $key;
        }

        //记录搜索结果
        $_SESSION['project_referer'] = "/fc_project/index?".$page_info;

        $select_columns = "select %s from fc_project %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            if($data_type=='detail') {
                //获取录入人员名称
                $user = $this->pdo->getRow("select user_name,true_name,is_admin from sys_user where id='{$item['create_uid']}'");
                $res[$key]['true_name'] = $user['true_name'];
            }
            $res[$key]['city'] = $this->baseCode->city_code_option[$item['city_code']];
            $res[$key]['project_type_val'] = $this->baseCode->project_type_option[$item['project_type']];

            $res[$key]['city'] = $this->metaData->getNameByCode($item['city_code']);
            $this->borough_option = $this->metaData->getPairBaseCodeByType($item['city_code']);
            $res[$key]['borough_val'] = $this->borough_option[$item['borough']];

            $res[$key]['build_year_val'] = $this->build_year_option[$item['build_year']];

            $res[$key]['img_url_s'] = str_replace('.','_s.',$res[$key]['img_url']);
            $res[$key]['img_url_m'] = str_replace('.','_m.',$res[$key]['img_url']);

            //处理物业
            $_pm_type = explode(',',$item['pm_type']);
            foreach($_pm_type as $k=>$v){
                $res[$key]['pm_type_val'] .= $this->baseCode->pm_type_option[$v].',';
                if($v=='20301' ){
                    //获取住宅价格
                    $sql = "select price,price_min,price_max,price_average,area_min,area_max from fc_project_house where project_id=".$item['id'];
                    $price = $this->pdo->getRow($sql);
                    if(isset($price['price_min']) && isset($price['price_max'])){
                        $res[$key]['price'] = intval($price['price_min']).'-'.intval($price['price_max']);
                    }else{
                        if(isset($price['price'])){
                            $res[$key]['price'] = intval($price['price']);
                        }
                    }
                    $res[$key]['area'] = intval($price['area_min']).'-'.intval($price['area_max']);
                }
            }
            $res[$key]['pm_type_val'] = substr($res[$key]['pm_type_val'],0,-1);
            //处理楼盘属性
            if(!empty($item['attribute'])) {
                $_attribute = explode(',', $item['attribute']);
                foreach ($_attribute as $a) {
                    $res[$key]['attribute_val'][] = $this->attribute_option[$a];
                }
            }
            //处理楼盘标签
            $res[$key]['label_val']= explode(',',$item['label']);
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 楼栋搜索 */
    public function searchBuild($data){
        $project_id = trim(isset($data["project_id"])?$data["project_id"]:0);
        $orderField = isset($data['sort']) ? $data['sort'] : 'build_no';
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';
        $pageSize = isset($data['page_size']) ? $data['page_size'] : 15;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where flag=1 and project_id='.$project_id.' ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['project_id'] = $project_id;
        $page_info ="sort=".$orderField."&sort_value=".$orderValue."&page=".$currentPage."&";

        $select_columns = "select %s from fc_project_build %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'Build');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['build_suffix_val'] = $this->build_suffix_option[$item['build_suffix']];
            $res[$key]['tableSum'] = $item['layer_num']*$item['layer_family_num'];
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 户型搜索 */
    public function searchHuxing($data){
        $project_id = trim(isset($data["project_id"])?$data["project_id"]:0);
        $orderField = isset($data['sort']) ? $data['sort'] : 'mode_quantity';
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';
        $pageSize = isset($data['page_size']) ? $data['page_size'] : 15;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where flag=1 and project_id='.$project_id.' ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['project_id'] = $project_id;
        $page_info ="sort=".$orderField."&sort_value=".$orderValue."&page=".$currentPage."&";

        //户型名称或者楼书名称
        if(isset($data['name']) && !empty($data['name'])){
            $where .= " and name like '%".$data['name']."%' or book_name like '%".$data['name']."%'";
            $page_info .= "name=".$data['name']."&";
            $filter['name'] = $data['name'];
        }

        $select_columns = "select %s from fc_project_mode %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $field = 'id,create_uid,create_date,flag,sort,name,code,project_id,layer_num,floor_hight,area_constru,area_in,diagram_img';
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'Mode');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 价格搜索 */
    public function searchPrice($data){
        $project_id = trim(isset($data["project_id"])?$data["project_id"]:0);
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';
        $pageSize = isset($data['page_size']) ? $data['page_size'] : 15;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where project_id='.$project_id.' ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['project_id'] = $project_id;
        $page_info ="sort=".$orderField."&sort_value=".$orderValue."&page=".$currentPage."&";

        //物业类型
        if(isset($data['pm_type']) && !empty($data['pm_type'])){
            $where .= " and pm_type = '%".$data['pm_type']."%'";
            $page_info .= "pm_type=".$data['pm_type']."&";
            $filter['name'] = $data['pm_type'];
        }

        $select_columns = "select %s from fc_project_price %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'Price');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['status_val'] = $this->baseCode->price_status_option[$item['status']];
            $res[$key]['start_date_val']=date('Y-m-d H:i', $item['start_date']);
            $res[$key]['pm_type_val']=$this->baseCode->pm_type_option[$item['pm_type']];
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 动态搜索 */
    public function searchDynamic($data){
        $project_id = trim(isset($data["project_id"])?$data["project_id"]:0);
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';
        $pageSize = isset($data['page_size']) ? $data['page_size'] : 15;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where flag=1 and project_id='.$project_id.' ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['project_id'] = $project_id;
        $page_info ="sort=".$orderField."&sort_value=".$orderValue."&page=".$currentPage."&";

        //物业类型
        if(isset($data['type']) && !empty($data['type'])){
            $where .= " and type = '%".$data['type']."%'";
            $page_info .= "type=".$data['type']."&";
            $filter['name'] = $data['type'];
        }

        $select_columns = "select %s from fc_project_dynamic %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'Price');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['flag_val'] = $this->baseCode->flag_option[$item['flag']];
            $res[$key]['start_date_val']=date('Y-m-d H:i', $item['start_date']);
            $res[$key]['type_val']=$this->baseCode->dynamic_type_option[$item['type']];
            $res[$key]['origin_val']=$this->baseCode->dynamic_origin_option[$item['origin']];
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 预售搜索 */
    public function searchLicense($data){
        $project_id = trim(isset($data["project_id"])?$data["project_id"]:0);
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';
        $pageSize = isset($data['page_size']) ? $data['page_size'] : 15;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where flag=1 and project_id='.$project_id.' ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['project_id'] = $project_id;
        $page_info ="sort=".$orderField."&sort_value=".$orderValue."&page=".$currentPage."&";

        //物业类型
        if(isset($data['type']) && !empty($data['type'])){
            $where .= " and type = '%".$data['type']."%'";
            $page_info .= "type=".$data['type']."&";
            $filter['name'] = $data['type'];
        }

        $select_columns = "select %s from fc_project_license %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'Price');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['flag_val'] = $this->baseCode->flag_option[$item['flag']];
            $res[$key]['cert_date_val']=date('Y-m-d H:i', $item['cert_date']);//发证时间
            $res[$key]['fitment_type_val']=$this->fitment_type_option[$item['fitment_type']];
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 获取楼盘详情 */
    public function getProjectInfo($project_id,$pm_type='20301',$data_type="base"){
        $sql = "select * from fc_project where id=" . $project_id;
        //初始数据
        $Info = $this->pdo->getRow($sql);
        $Info['pm_type'] = explode(",", $Info['pm_type']);
        $Info['build_type'] = explode(",", $Info['build_type']);
        $Info['borough_val'] = $this->borough_option[$Info['borough']];
        $Info['direction'] = $this->direction_option[$Info['direction']];

        $Info['create_date'] = date('Y-m-d H:i',$Info['create_date']);

        if($data_type=='detail') {
            $sysUser = new SysUser();
            //首录人
            $Info['creater'] = $sysUser->getUserNameById($Info['create_uid']);
            //获取负责人信息
            $Info['owner'] = $sysUser->getUserInfoById($Info['owner_uid']);
            $Info['flag_val'] =$Info['flag']==1?'有效':'无效';
        }

        //获取楼盘相册
        $Info['pics'] = $this->getProjectPic($project_id,0,6,array('code'=>'20902'));

        //获取置业顾问
        $sql = "select true_name,sex,mobile,headimgurl from sys_user where id in ({$Info['sale_uid']}) limit 0,4";
        $Info['saler'] = $this->pdo->getAll($sql);

        //根据物业类型,获取对应项目信息
        $Info['pm_info'] = $this->pmProjectInfo($Info['id'],$pm_type);//获取对应物业类型的详细数据
        //处理物业类型
        foreach($Info['pm_type'] as $key=>$val){
            $Info['pm_type_val'][] = $this->tranPmType($val,$this->baseCode->pm_type_option,2);
        }
        //处理楼盘属性
        if(!empty($Info['attribute'])) {
            $_attribute = explode(',', $Info['attribute']);
            foreach ($_attribute as $a) {
                $Info['attribute_val'][] = $this->attribute_option[$a];
            }
        }

        //处理楼盘标签
        $Info['label_val']= explode(',',$Info['label']);

        $Info['build_struct_val'] = $this->build_struct_option[$Info['build_struct']];

        return $Info;
    }

    /* 获取楼盘预售 */
    public function getLicense($project_id){
        $sql = "select license,number,cert_date,family_num,lottery_range from fc_project_license where project_id={$project_id} and flag=1";
        $license = $this->pdo->getAll($sql);
        foreach ($license as $key=>$item){
            $license[$key]['cert_date_val'] = date('Y-m-d',$item['cert_date']);
            $license[$key]['family_num'] = $item['family_num'].'套';
        }
        return $license;
    }

    /* 获取置业顾问 */
    public function getProjectSaler($project_id){
        $sql = "select sale_uid from fc_project where id=" . $project_id;
        $project = $this->pdo->getRow($sql);
        $sale_uid = $project['sale_uid'];
        $sql = "select true_name,sex,mobile from sys_user where id in ({$sale_uid})";
        $Info = $this->pdo->getAll($sql);
        return $Info;
    }

    /* 获取项目周边 */
    public function getProjectCircum($project_id){
        $sql = "select market,school,hospital,subway,traffic from fc_project where id=" . $project_id;
        $Info = $this->pdo->getRow($sql);
        $rlt = array();
        $market = explode('#',$Info['market']);
        foreach ($market as $key=>$item){
            if($item!='') {
                $_item = explode('|', $item);
                $local = explode('-',$_item[1]);
                $circum['id'] = $key+1;
                $circum['name'] = $_item[0];
                $circum['longitude'] = $local[0];
                $circum['latitude']  = $local[1];
                $circum['iconPath'] = '/images/icon_map_gray.png';
                $rlt['market'][] = $circum;
            }
        }
        $school = explode('#',$Info['school']);
        foreach ($school as $key=>$item){
            if($item!='') {
                $_item = explode('|', $item);
                $local = explode('-',$_item[1]);
                $circum['id'] = $key+1;
                $circum['name'] = $_item[0];
                $circum['longitude'] = $local[0];
                $circum['latitude']  = $local[1];
                $circum['iconPath'] = '/images/icon_map_gray.png';
                $rlt['school'][] = $circum;
            }
        }
        $hospital = explode('#',$Info['hospital']);
        foreach ($hospital as $key=>$item){
            if($item!='') {
                $_item = explode('|', $item);
                $local = explode('-',$_item[1]);
                $circum['id'] = $key+1;
                $circum['name'] = $_item[0];
                $circum['longitude'] = $local[0];
                $circum['latitude']  = $local[1];
                $circum['iconPath'] = '/images/icon_map_gray.png';
                $rlt['hospital'][] = $circum;
            }
        }
        $subway = explode('#',$Info['subway']);
        foreach ($subway as $key=>$item){
            if($item!='') {
                $_item = explode('|', $item);
                $local = explode('-',$_item[1]);
                $circum['id'] = $key+1;
                $circum['name'] = $_item[0];
                $circum['longitude'] = $local[0];
                $circum['latitude']  = $local[1];
                $circum['iconPath'] = '/images/icon_map_gray.png';
                $rlt['subway'][] = $circum;
            }
        }
        $traffic = explode('#',$Info['traffic']);
        foreach ($traffic as $key=>$item){
            if($item!='') {
                $_item = explode('|', $item);
                $local = explode('-',$_item[1]);
                $circum['id'] = $key+1;
                $circum['name'] = $_item[0];
                $circum['longitude'] = $local[0];
                $circum['latitude']  = $local[1];
                $circum['iconPath'] = '/images/icon_map_gray.png';
                $rlt['traffic'][] = $circum;
            }
        }
        return $rlt;
    }

    /* 获取楼盘相册 */
    public function getProjectPic($project_id,$start=0,$num=100,$data=array(),$order='sort desc'){
        $where = 'where 1=1 ';
        //城市区域
        $code = isset($data['code'])?$data['code']:0;
        if($code) {
            $where .= " and p.code={$code}";
        }
        $sql = "select p.id,p.create_date,p.code,p.pm_type,p.project_id,p.attach_id,p.title,p.des,p.is_show,a.url,u.true_name from fc_project_pic as p left join fc_project_attach as a on p.attach_id=a.id left join sys_user as u on p.create_uid=u.id ".$where." and p.flag=1 and p.project_id={$project_id}  order by p.".$order." limit ".$start.",".$num;
        $res = $this->pdo->getAll($sql);
        foreach ($res as $key=>$item){
            $res[$key]['url_m'] = str_replace('.','_m.',$res[$key]['url']);
            $res[$key]['url_s'] = str_replace('.','_s.',$res[$key]['url']);
        }
        return $res;
    }

    /* 获取楼盘户型 */
    public function getProjectMode($project_id,$start=0,$num=100){
        $sql = "select p.id,p.create_date,p.name,p.project_id,p.book_code,p.book_name,p.area_constru,p.price_ini,p.diagram_img,p.shi,u.true_name from fc_project_mode as p left join sys_user as u on p.create_uid=u.id where p.flag=1 and p.project_id={$project_id} order by p.id desc limit ".$start.",".$num;
        $res = $this->pdo->getAll($sql);
        foreach ($res as $key=>$item){
            $res[$key]['url_m'] = str_replace('.','_m.',$res[$key]['diagram_img']);
            $res[$key]['url_s'] = str_replace('.','_s.',$res[$key]['diagram_img']);
            $res[$key]['price'] = number_format(($item['area_constru']*$item['price_ini'])/10000,0);
        }
        return $res;
    }

    /* 更新浏览量 */
    public function hitNum($id){
        $rlt = $this->pdo->doSql("update fc_project set hits_num=hits_num+1 where id={$id}");
        return $rlt;
    }

    /* 获取楼盘海报图片 */
    public function getProjectPosterPic($project_id,$start=0,$num=100){
        $sql = "select p.id,p.create_date,p.code,p.pm_type,p.project_id,p.attach_id,p.title,p.des,p.is_show,a.url from fc_project_pic as p left join fc_project_attach as a on p.attach_id=a.id where p.flag=1 and p.code=20908 and p.project_id={$project_id} order by p.sort asc limit ".$start.",".$num;
        $res = $this->pdo->getAll($sql);
        foreach ($res as $key=>$item){
            $res[$key]['url_m'] = str_replace('.','_m.',$res[$key]['url']);
            $res[$key]['url_s'] = str_replace('.','_s.',$res[$key]['url']);
        }
        return $res;
    }

    /* 物业类型转换 */
    public function tranPmType($pm_type,$pm_type_option){
        $pm_type = explode(",", $pm_type);
        $result = array();
        foreach ($pm_type as $val){
            $result['val']=$pm_type_option[$val];
            switch ($val){
                case '20301'://住宅
                    $result['font_color']='success';
                    $result['bg_color']='success';
                    break;
                case '20302'://公寓
                    $result['font_color']='dark';
                    $result['bg_color']='dark';
                    break;
                case '20303'://别墅
                    $result['font_color']='dark';
                    $result['bg_color']='dark';
                    break;
                case '20306'://写字楼
                    $result['font_color']='dark';
                    $result['bg_color']='dark';
                    break;
                default:
                    $result['font_color']='dark';
                    $result['bg_color']='dark';
                    break;
            }
        }
        return $result;
    }

    /* 户型转换 */
    public function tranHuxing($ting='',$shi='',$type=1){
        $shiStr = '';
        $tingStr = '';
        switch($shi){
            case '1':
                $shiStr ='一室';
                break;
            case '2':
                $shiStr ='二室';
                break;
            case '3':
                $shiStr ='三室';
                break;
            case '4':
                $shiStr ='四室';
                break;
            case '5':
                $shiStr ='五室以上';
                break;
            default:
                $shiStr ='五室以上';
                break;
        }
        switch($ting){
            case '1':
                $tingStr = '一厅';
                break;
            case '2':
                $tingStr = '二厅';
                break;
            case '3':
                $tingStr = '三厅';
                break;
            case '4':
                $tingStr = '四厅';
                break;
            default:
                $tingStr = '四厅以上';
                break;
        }
        $huxing = $shiStr.$tingStr;
        return $huxing;
    }

    /* 根据物业类型返回表名 */
    public function getPmTypeTable($pm_type){
        $result = 'house';
        switch($pm_type){
            case '20303'://别墅
                $result ='villa';
                break;
            case '20308'://商业
                $result ='business';
                break;
            case '20306'://写字楼
                $result ='office';
                break;
            case '20302'://公寓
                $result ='apartment';
                break;
            case '20301'://住宅
                $result ='house';
                break;
            default:
                $result ='house';
                break;
        }

        return $result;
    }

    /* 根据物业类型获取详细信息 */
    public function pmProjectInfo($project_id,$pm_type){
        $table = $this->getPmTypeTable($pm_type);
        $sql = "select * from fc_project_".$table." where project_id=".$project_id;
        $Info = $this->pdo->getRow($sql);
        $Info['live_date_val'] = date('Y-m-d',$Info['live_date']);
        $Info['open_date_val'] = date('Y-m-d',$Info['open_date']);
        $Info['pm_type'] = $pm_type;
        $Info['price'] = $Info['price'].'万元';
        $Info['must_price'] = "50万";//验资金额
        $Info['price_average'] = $Info['price_average'].'元/m²';//均价
        $Info['unit_price'] = $Info['price_min'] . "-" . $Info['price_max'] . "元/m²";//单价
        $Info['status_val'] = $this->status_option[$Info['status']];
        $Info['status_color'] = $this->statusColor($Info['status']);
        if($Info['price_min']==0 || $Info['price_max']==0){
            $Info['cprice'] = $Info['price_average'];
        }else{
            $Info['cprice'] = $Info['unit_price'];
        }
        $Info['huxing_area'] = "约".$Info['area_min'] . "-" . $Info['area_max'] . "m²";//主力户型
        $Info['fitment_type_val'] = $this->fitment_type_option[$Info['fitment_type']];
        $Info['use_age'] = isset($Info['use_age'])?$Info['use_age'].'年':'';
        $Info['cubage'] = isset($Info['cubage'])?$Info['cubage'].'%':'';
        $Info['greenbelt'] = isset($Info['greenbelt'])?$Info['greenbelt'].'%':'';
        //$Info['parking_num'] = $Info['parking_num'].'个';
        $Info['fitment_type_val'] = $this->fitment_type_option[$Info['fitment_type']];
        return $Info;
    }

    /* 更新价格项目表均价 */
    public function updateAvePrice($project_id,$pm_type,$ave_price){
        $table = $this->getPmTypeTable($pm_type);
        //echo 'update fc_project set red_'.$table.'_price_average='.$ave_price.' where id='.$project_id;exit;
        $rlt = $this->pdo->doSql('update fc_project set red_'.$table.'_price_average='.$ave_price.' where id='.$project_id);
        return $rlt;
    }

    /* 更新最大价格 */
    public function updateMaxPrice($project_id,$pm_type,$price){
        $table = $this->getPmTypeTable($pm_type);
        //echo 'update fc_project set red_'.$table.'_price_average='.$ave_price.' where id='.$project_id;exit;
        $rlt = $this->pdo->doSql('update fc_project_'.$table.' set price_max='.$price.' where project_id='.$project_id);
        return $rlt;
    }

    /* 更新最小价格 */
    public function updateMinPrice($project_id,$pm_type,$price){
        $table = $this->getPmTypeTable($pm_type);
        //echo 'update fc_project set red_'.$table.'_price_average='.$ave_price.' where id='.$project_id;exit;
        $rlt = $this->pdo->doSql('update fc_project_'.$table.' set price_min='.$price.' where project_id='.$project_id);
        return $rlt;
    }

    /* 根据项目Id获取楼栋check */
    public function getBuildList($project_id,$start=0,$num=30,$order='build_no asc'){
        //获取该项目楼栋
        $sql = "select id,build_no,unit_no from fc_project_build where flag=1 and project_id={$project_id} ORDER BY ".$order." limit ".$start.",".$num;
        $buildList = $this->pdo->getAll($sql);
        return $buildList;
    }

    /* 根据项目Id获取项目名称 */
    public function getNameById($id) {
        $sql = "SELECT id,name FROM %s WHERE id = %d AND flag = 1 ";
        $sql = sprintf($sql, DB_PREFIX_FC."project", $id);
        $rlt = $this->pdo->getRow($sql);
        $name = $rlt['name'];
        return $name;
    }

    /* 根据项目小区名 查找小区列表 */
    public function getProjectNameListByName($name='',$field="id,name,borough,region,address"){
        $list = array();
        if(!empty($name)) {
            $sql = "select ".$field." from fc_project where flag=1 and name like '%{$name}%'";
            $list = $this->pdo->getAll($sql);
        }
        return $list;
    }

    /* 根据项目小区名 查找小区列表 */
    public function getProjectNameById($id,$field="id,name"){
        $sql = "select ".$field." from fc_project where id=" .$id;
        $rlt = $this->pdo->getRow($sql);
        return $rlt;
    }

    /* 关注楼盘 */
    public function attentNum($project_id,$opt='sure'){
        if($opt=='sure'){
            $rlt = $this->pdo->doSql('update fc_project set atme_num=atme_num+1 where id=' . $project_id);
            return $rlt;
        }else{
            //取消关注楼盘
            $rlt = $this->pdo->doSql('update fc_project set atme_num=atme_num-1 where id=' . $project_id);
            return $rlt;
        }
    }

    /*
	 * 获取地区信息
     * @param string $code 地区编码
	 * @param string $type 1:省级地区 2：市级地区 3：行政区
     * */
    public function obtainRegion($code,$type){
        $code = (string)$code;
        if(preg_match("/^(0|[1-9][0-9]*)$/",$code)){
            $code_1 = $code[0].$code[1];
            $code_2 = $code[2].$code[3];
            $code_3 = $code[4].$code[5];

            if($type == 1){
                $data = $this->pdo->getAll("select id,code,name,parent_code from sys_metadata where code like '%0000' and parent_code = '107' and flag = 1 ORDER BY code ASC");
            }else if($type == 2){
                $data = $this->pdo->getAll("select id,code,name,parent_code from sys_metadata where code like '$code_1%$code_3' and code != '$code' and flag = 1 ORDER BY code ASC");
            }else if($type == 3){
                $data = $this->pdo->getAll("select id,code,name,parent_code from sys_metadata where code like '$code_1$code_2%' and code != '$code' and flag = 1 ORDER BY code ASC");
            }

            if(isset($data) && !empty($data)){
                return $data;
            }
        }
        return "城市获取失败";
    }

    /* 返回项目销售状态颜色 */
    private function statusColor($status){
        switch ($status){
            case '0':
                $color='gray';
                break;
            case '22201':
                $color='orange';
                break;
            case '22202':
                $color='green';
                break;
            default:
                $color='red';
                break;
        }
        return $color;
    }
    
}
